package cn.dogger.easyboot.nio.init;

import cn.dogger.easyboot.common.exception.SocketException;
import cn.dogger.easyboot.log.utils.Log;
import cn.dogger.easyboot.nio.handler.SocketUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author dogger
 * 2022/11/21 14:19
 */
@Component
public class WebSocketInit {

    /**
     * socket端口
     */
    private static final Integer PORT = 8989;

    /**
     * socket客户端连接集合
     */
    public static Selector selector;

    public static Selector getSelector() {
        return selector;
    }

    public static void setSelector(Selector selector) {
        WebSocketInit.selector = selector;
    }

    private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(1, 1,
            180L, TimeUnit.SECONDS,
            new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * FileChannel： 用于文件的数据读写
     * DatagramChannel： 用于UDP的数据读写
     * SocketChannel： 用于TCP的数据读写，一般是客户端实现
     * ServerSocketChannel: 允许我们监听TCP链接请求，每个请求会创建会一个SocketChannel，一般是服务器实现
     */
    public WebSocketInit() {
        Runnable runnable = () -> {
            new Log(getClass());
            Log.info("初始化socket");
            try {
                ServerSocketChannel serverSocket = ServerSocketChannel.open();
                serverSocket.socket().bind(new InetSocketAddress(PORT));
                //设置非阻塞，默认为true；
                serverSocket.configureBlocking(false);
                //创建epoll，多路复用器
                selector = Selector.open();
                //ServerSocketChannel注册进selector，并且该selector对客户端accept感兴趣
                serverSocket.register(selector, SelectionKey.OP_ACCEPT);
                while (true) {
                    selector.select();
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        //如果是SelectionKey.OP_ACCEPT，就进行客户端连接事件的注册；如果是SelectionKey.OP_READ，就进行读取
                        if (key.isAcceptable()) {
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            //开启非阻塞后此方法不会阻塞，不然会一直卡在这里等待连接
                            //NIO的非阻塞是由系统内部实现的，调用了linux内核的accept函数
                            SocketChannel channel = serverSocketChannel.accept();
                            //设置为非阻塞，否则后面读取到缓冲区时会变阻塞。
                            channel.configureBlocking(false);
                            //客户端连接后，注册成read
                            channel.register(selector, SelectionKey.OP_READ);
                            Log.info("客户端{}连接", channel.hashCode());
                        }else if(key.isReadable()) {
                            SocketChannel channel = (SocketChannel) key.channel();
                            SocketUtils.socketRead(channel);
                        }
                    }
                }
            } catch (IOException e) {
                throw new SocketException(e);
            }
       };
        THREAD_POOL_EXECUTOR.execute(runnable);

    }
}
